<template>
    <uni-popup class="share-common-popup" ref="shareCommonPopupRef" :safe-area="false">
        <slot>
            <view class="share-common-popup-main">
                <button
                    class="share-common-popup-icon"
                    v-for="{ name, label } in shareList"
                    :key="name"
                    @tap="handleIconTap(name)"
                    :open-type="name === 'wechat' ? 'share' : ''">
                    <image
                        class="share-common-popup-image"
                        :src="getImgOssUrl(`/ui-prod-2.12.0/share_${name}_icon.png`)"></image>
                    <view>{{ label }}</view>
                </button>
            </view>
            <view class="share-common-popup-bottom" @tap="handlePopup('close')">取消</view>
        </slot>
    </uni-popup>
    <!-- todo:海报 -->
    <uni-popup class="posters-view-default" ref="postersPopup" :mask-click="true">
        <view class="posters-view" id="posters-view" ref="postersView">
            <slot>
                <image class="posters-view-img" :src="shareAppMessage?.imageUrl"></image>
                <slot name="bottom">
                    <view class="posters-view-bottom">
                        <view class="posters-view-bottom-left">
                            <view class="bottom-left-top">
                                <image :src="avatarUrl" class="custom-avatar"></image>
                                <view class="custom-nickname"
                                    >{{ nickname }}<text class="custom-nickname-tip">为你推荐</text></view
                                >
                            </view>
                            <slot name="context">
                                <view class="custom-title">{{ shopName }}</view>
                                <view class="custom-desc">{{ shareAppMessage?.title }}</view>
                            </slot>
                        </view>
                        <view class="posters-view-bottom-right">
                            <image class="bottom-right-image" :show-menu-by-longpress="true" :src="qrcodeImg"></image>
                            <view class="bottom-right-text">长按识别查看</view>
                        </view>
                    </view>
                </slot>
                <button class="posters-view-button" @tap="handleSavePosters">保存图片</button>
                <image
                    @tap="closePopup"
                    class="posters-view-close"
                    :src="getImgOssUrl(`/ui-prod-2.12.0/share_close_icon.png`)"></image>
            </slot>
        </view>
    </uni-popup>
    <uni-popup class="photo-view-default" ref="photoPopupRef" :mask-click="true">
        <view class="photo-popup">
            <view class="photo-popup-tip">您已禁止了添加到相册权限，请前往权限页面设置开启</view>
            <view class="photo-last"><view class="photo-btn" @tap="handleRoutePermission"> 立即设置 </view></view>
        </view>
    </uni-popup>
    <canvasdrawer v-if="painting?.views?.length" :painting="painting" class="canvasdrawer" @getImage="eventGetImage" />
</template>

<script setup>
import { ref, reactive } from 'vue';
import { getImgOssUrl, checkToken } from '@/commons/utils.js';
import { debounce, throttle } from 'lodash';
import { onShareAppMessage, onShow } from '@dcloudio/uni-app';
import request from '@/request';
import storage from '@/commons/storage';
import { getCorpInfo } from '@/hooks';
import canvasdrawer from '@/components/uniapp-canvas-drawer/uniapp-canvas-drawer';

const props = defineProps({
    pageInfo: {
        type: Object,
        default: () => ({
            pageTitle: '', // 分享的页面标题，非必传
            linkPrefix: '', // 链接前缀，非必传
            data: {} // 分享的页面数据
        })
    },
    posters: {
        type: Object,
        default: () => ({
            // 海报相关
        })
    },
    slotViews: {
        type: Function,
        default: () => null
    },
    shareAppMessage: {
        type: Object,
        default: () => ({
            // 分享信息，供分享好友朋友圈使用，其中也包含页面path，供复制链接使用
        })
    }
});

// 读取缓存数据
let shopName = ref(storage.get('shopName'));
let nickname = ref(storage.get('nickname') || '你的好友');
let defaultImg = ref(getImgOssUrl('/ui-prod-2.0.0/errorImg.png'));
let avatarUrl = ref(storage.get('avatar') || getImgOssUrl('/ui-prod-2.7.0/avatar.png'));

const shareCommonPopupRef = ref(null);

const shareList = reactive([
    {
        name: 'wechat',
        label: '发给微信好友'
    },
    {
        name: 'posters',
        label: '生成分享海报'
    },
    {
        name: 'link',
        label: '复制链接'
    }
]);

// 海报ref
let postersPopup = ref();
const closePopup = () => {
    postersPopup?.value?.close();
};

let qrcodeImg = ref(); // 二维码
let isLoading = ref(false);
// 控制图标点击
const handleIconTap = debounce(type => {
    if (type === 'wechat') {
        // 微信分享根据按钮:open-type="'share'"判断,无需事件
        handlePopup('close');
        return;
    }
    const types = {
        // wechat() {},
        posters: async () => {
            // 打开海报
            uni.showLoading({
                title: '生成海报中...',
                mask: true
            });
            isLoading.value = true;
            const { path } = props?.shareAppMessage || {};
            if (path) {
                const [path0, ...rest] = path.split('?');
                const { data } = await request('spreadQrcode', {
                    path: (path0 || '').substring(1),
                    params: rest && rest.length ? rest.join('?') : ''
                });
                qrcodeImg.value = (data || {})?.url;
            }
            isLoading.value && uni.hideLoading();
            isLoading.value = false;
            handlePopup('close');
            postersPopup?.value?.open('center');
        },
        link: async () => {
            // 复制链接
            uni.showLoading({
                title: '生成链接中...',
                mask: true
            });
            isLoading.value = true;
            const { path } = props?.shareAppMessage || {};
            // todo:请求接口
            const pageUrl = (path || '').substring(1);
            const { data } = await request('shareShortLink', {
                pageUrl,
                pageTitle: props?.pageInfo?.pageTitle // todo页面标题
            });
            uni.hideLoading();
            if (!data?.shortLink) {
                uni.showToast({
                    title: '小程序链接复制失败',
                    icon: 'none'
                });
                return;
            }
            uni.setClipboardData({
                data: props?.pageInfo?.linkPrefix + data.shortLink,
                success: () => {
                    uni.showToast({
                        title: '小程序链接复制成功',
                        icon: 'none'
                    });
                    // todo: 分享成功关闭弹窗
                    handlePopup('close');
                }
            });
        }
    };
    types[type]();
}, 800);

const handlePopup = async type => {
    const currentRef = shareCommonPopupRef?.value;
    if (type !== 'close') {
        // 重新获取缓存值
        shopName.value = storage.get('shopName');
        nickname.value = storage.get('nickname') || '你的好友';
        defaultImg.value = ref(getImgOssUrl('/ui-prod-2.0.0/errorImg.png'));
        avatarUrl.value = storage.get('avatar') || getImgOssUrl('/ui-prod-2.7.0/avatar.png');
        if (!storage.get('ZW_TENANT_ID') || !storage.get('ZW_CORP_ID')) {
            await getCorpInfo();
        }
        if ((nickname.value == '你的好友' || /avatar\.png/.test(avatarUrl.value)) && (await checkToken())) {
            const res = await request('memberInfo');
            nickname.value = res?.data?.nickname || '你的好友';
            avatarUrl.value = res?.data?.avatar || getImgOssUrl('/ui-prod-2.7.0/avatar.png');
        }
        currentRef?.open(type || 'bottom');
    } else {
        currentRef?.close();
    }
};

// 保存图片
let painting = reactive({});
let postersView = ref();
const shareImage = ref();
let photoPopupRef = ref();
const eventGetImage = res => {
    isLoading.value && uni.hideLoading();
    isLoading.value = false;

    // const { tempFilePath, errMsg } = event.detail

    // let result = null;
    let tempFilePath = null;
    let errMsg = null;

    // #ifdef MP-WEIXIN
    // console.log('event', event);
    // result = event.detail.__args__;
    // tempFilePath = result[0].tempFilePath;
    // errMsg = result[0].errMsg;
    // #endif

    // #ifdef APP-PLUS
    // result = event;
    tempFilePath = res?.tempFilePath;
    errMsg = res?.errMsg;
    // #endif

    if (res?.errMsg === 'canvasdrawer:ok') {
        // #ifdef MP-WEIXIN
        shareImage.value = res?.tempFilePath;
        // #endif

        // #ifdef APP-PLUS
        // shareImage.value = 'file:///' + plus.io.convertLocalFileSystemURL(tempFilePath);
        // #endif
        // painting = {};
        uni.saveImageToPhotosAlbum({
            filePath: shareImage.value,
            success(res) {
                // uni.showToast({
                //     title: '图片保存成功~',
                //     icon: 'success',
                //     duration: 2000
                // });
                photoPopupRef?.value?.close();
                const prefix = /pages\/tabbar\/home/.test(props.shareAppMessage?.path) ? '店铺' : '商品';
                uni.showToast({
                    title: prefix + '海报已保存至你的相册',
                    icon: 'none',
                    duration: 2000
                });
                closePopup();
            },
            fail(error) {
                if (error?.errMsg.includes('deny')) {
                    closePopup();
                    photoPopupRef?.value.open('center');
                }
                // uni.showModal({
                //     title: '您已禁止了添加到相册权限，请前往权限页面设置开启',
                //     icon: 'none',
                //     showCancel: false,
                //     success: () => {
                //         uni.openSetting({});
                //     }
                // });
            }
        });
    } else {
    }
};
const getPainting = () => {
    uni.showLoading({
        title: '图片生成中...',
        mask: true
    });
    isLoading.value = true;
    // todo:之后根据屏幕分辨率计算高
    const { windowWidth, windowHeight } = uni.getSystemInfoSync();
    const width = windowWidth;
    const height = width;
    let views = [
        // {
        //     type: 'image',
        //     url: bgUrl,
        //     top: 0,
        //     left: 0,
        //     width: width,
        //     height: width * 1.46
        // },
        // {
        //     type: 'image',
        //     url: avatarUrl,
        //     top: height - 74,
        //     left: 16,
        //     width: 56,
        //     height: 56
        // },
        {
            type: 'image',
            url: props.shareAppMessage?.imageUrl,
            top: 0,
            left: 0,
            width: width,
            height: height
        },
        {
            type: 'image',
            url: avatarUrl.value,
            top: height + 15,
            left: 15,
            width: 28,
            height: 28,
            isCircle: true
        },
        {
            type: 'image',
            url: qrcodeImg.value || defaultImg.value,
            left: width - 96,
            top: height + 15,
            width: 81,
            height: 81
        },
        {
            type: 'text',
            content: nickname.value + '  ' + '为你推荐',
            fontSize: 14,
            lineHeight: 22,
            color: '#666666',
            textAlign: 'left',
            top: height + 22,
            left: 49,
            width: 220,
            MaxLineNumber: 1,
            breakWord: true
            // bolder: true
        },
        // {
        //     type: 'text',
        //     content: '为你推荐',
        //     fontSize: 14,
        //     lineHeight: 22,
        //     color: '#666666',
        //     textAlign: 'left',
        //     top: height + 22,
        //     left: 53 + (nickname.value.length * 14 >= 100 ? 103 : nickname.value.length * 14),
        //     MaxLineNumber: 1,
        //     breakWord: true,
        //     bolder: true
        // },
        {
            type: 'text',
            content: '长按识别查看',
            fontSize: 12,
            lineHeight: 14,
            color: '#666666',
            textAlign: 'left',
            top: height + 110,
            left: width - 90,
            MaxLineNumber: 1,
            breakWord: true
        }
    ];
    if (props?.slotViews()) {
        // slot context,todo: 以后全部的slot
        const slotViews = props.slotViews(height);
        views.push(...slotViews);
    } else {
        views.push(
            {
                type: 'text',
                content: shopName,
                fontSize: 16,
                lineHeight: 14,
                color: '#333333',
                textAlign: 'left',
                top: height + 52,
                left: 15,
                width: 200,
                MaxLineNumber: 1,
                breakWord: true
            },
            {
                type: 'text',
                content: props?.shareAppMessage?.title,
                fontSize: 14,
                lineHeight: 22,
                color: '#333333',
                textAlign: 'left',
                top: height + 82,
                left: 15,
                width: 200,
                MaxLineNumber: 2,
                breakWord: true
            }
        );
    }
    Object.assign(painting, {
        width,
        height: width <= 320 ? width / 0.7 : width / 0.73,
        isPixelRatio: true,
        views
    });
};
const handleSavePosters = () => {
    if (!shareImage.value) {
        Object.assign(painting, {
            width: null,
            height: null,
            isPixelRatio: false,
            views: []
        });
        getPainting();
    } else {
        uni.saveImageToPhotosAlbum({
            filePath: shareImage.value,
            success(res) {
                photoPopupRef?.value.close();
                // todo:以后自定义
                const prefix = /pages\/tabbar\/home/.test(props.shareAppMessage?.path) ? '店铺' : '商品';
                uni.showToast({
                    title: prefix + '海报已保存至你的相册',
                    icon: 'success',
                    duration: 2000
                });
                closePopup();
            },
            fail(error) {
                if (error?.errMsg.includes('deny')) {
                    closePopup();
                    photoPopupRef?.value.open('center');
                }
                // uni.showModal({
                //     title: '您已禁止了添加到相册权限，请前往权限页面设置开启',
                //     icon: 'none',
                //     showCancel: false,
                //     success: () => {
                //         uni.openSetting({});
                //     }
                // });
            }
        });
    }
};

const handleRoutePermission = () => {
    photoPopupRef?.value.close();
    uni.openSetting({});
};

// todo:onShareAppMessage
onShareAppMessage(() => {
    return {
        ...props?.shareAppMessage
    };
});
onShow(() => {
    isLoading.value && uni.hideLoading();
    isLoading.value = false;
});

defineExpose({
    handlePopup
});
</script>

<style lang="scss" scoped src="./index.scss"></style>
